import config from '../config';
import angular from 'angular'
import '@yunke/art-dialog'
import ui from '@yunke/core/ui'
import util from '@yunke/core/util'
import _ from 'lodash'
import '@yunke/jquery_pagination'
import 'angular-ui'
import '../../plugins/select2/select2'
import $ from "jquery"

const apiPrefix = window.G_CONFIG.api_prefix; //api前缀

angular.module('Invoice', ['ngUI', 'myNav']).service('invoiceService', [() => {
    return {
        onCloseInvoice($dialogScope, invoiceType) {
            if ($dialogScope.saveAndAdd === true) {
                if (invoiceType === 1) {
                    $('#addVoiceButton').trigger('click');
                }
                if (invoiceType === 2) {
                    $('#addMainVoiceButton').trigger('click');
                }
            }
        },
        addAndSaveBtn($dialog, $dialogScope) {
            $($dialog.node).find('[i-id=ok]').after(
                '<button type="button" i-id="okAdd" class="ui-dialog-autofocus" onclick="">确定并新增</button>');
            $($dialog.node).find('[i-id=okAdd]').on('click', function () {
                $dialogScope.saveAndAdd = true;
                $($dialog.node).find('[i-id=ok]').trigger('click');
            });
            $($dialog.node).find('[i-id=cancel]').on('click', function () {
                $dialogScope.saveAndAdd = false;
            });
        },
        onInvoiceShow($dialog, $dialogScope, invoiceType, oldInvoiceId) {
            /**
             * 打开发票编辑界面时初始化
             * invoiceType: 发票类型：1：新建发票，2：新建主发票，3：复制发票，4：编辑发票，5：查看发票, 6:红冲此发票
             * oldInvoiceId: 原发票id
             */
            if (invoiceType === 1 || invoiceType === 2) {
                this.addAndSaveBtn($dialog, $dialogScope);
            }

            //下拉框设置
            //发票类别
            $dialogScope.ddlConfigInvoiceCategory = {
                allowClear: false,
                data: [{
                    id: 1,
                    text: '服务票'
                }, {
                    id: 0,
                    text: '销售票'
                }],
                minimumResultsForSearch: 'Infinity'
            };

            //发票类型
            $dialogScope.ddlConfigInvoiceType = {
                allowClear: false,
                data: [{
                    id: 0,
                    text: '增值税普通发票'
                }, {
                    id: 1,
                    text: '增值税专用发票'
                }],
                minimumResultsForSearch: 'Infinity'
            };

            //摘要类型
            $dialogScope.ddlConfigInvoiceSummaryType = {
                allowClear: false,
                data: _.map(
                    ['软件技术服务费', '软件服务费', '服务费', '明源云客电子商务平台－移动销售系统V1.0', '明源云客来访登记系统V1.0', '广告费', '广告发布费'],
                    x => ({
                        id: x,
                        text: x
                    })),
                minimumResultsForSearch: 'Infinity'
            };

            //申请人
            $dialogScope.ddlConfigInvoiceProposer = {
                allowClear: false,
                ajax: {
                    url: apiPrefix + 'erp-interface/get-users',
                    dataType: 'json',
                    delay: 250,
                    data(term) {
                        return {
                            keyword: term,
                            limit: 10
                        };
                    },
                    results(json) {
                        let data = [];
                        if (json.retCode === '0') {
                            data = json.data;
                        }
                        return {
                            results: data
                        };
                    },
                    processResults(data) {
                        return {
                            results: data.items
                        };
                    },
                    cache: true
                },
                escapeMarkup(markup) {
                    return markup;
                }, // let our custom formatter work
                minimumInputLength: 1,
                onchange2(newVal) {
                    $dialogScope.invoiceInfo.user_name = newVal.UserName;
                    $dialogScope.invoiceInfo.area_name = newVal.BUName;
                },
                formatResult(repo) {
                    if (repo.loading) return repo.text;
                    return '<div class="clearfix" style="width: 300px;">' +
                    '<div class="clearfix">' +
                    '<div class="col-sm-6">' + repo.UserName + '</div>' +
                    '<div class="col-sm-18">' + repo.BUName + '</div>' +
                    '</div></div>';
                },
                formatSelection(repo) {
                    return repo.text;
                } // omitted for brevity, see the source of this page
            };

            //开票单位
            $dialogScope.ddlConfigInvoiceCompany = {
                allowClear: false,
                data: [],
                onchange2(newVal) {
                    $dialogScope.invoiceInfo.invoice_company_name = newVal.BUName;
                }
            };
            (function () {
                /**
                 * 获取开票单位
                 */
                $.ajax({
                    url: apiPrefix + '/invoice/get-invoice-business-unit',
                    type: 'GET',
                    dataType: 'json',
                    data: {
                        keyword: ''
                    },
                    success(json) {
                        if (Number(json.retCode) === 0) {
                            const ddlData = _.map(json.data, item => ({
                                id: item.BUGUID,
                                text: item.BUName
                            }))
                            $dialogScope.ddlConfigInvoiceCompany.data = ddlData;
                            //初始化开票单位为明源云客
                            if (!$dialogScope.invoiceInfo.invoice_company_id) {
                                $dialogScope.invoiceInfo.invoice_company_id = 'f775a92e-0071-11e5-bed8-00155d02c832';
                            }
                            $dialogScope.$applyAsync();
                        } else {
                            util.alert('获取开票单位失败：' + json.errMsg);
                        }
                    }
                });
            }());

            //初始化发票信息
            $dialogScope.invoiceInfo = {
                is_main_invoice: '0',
                invoice_category: '1',
                invoice_type: '0',
                invoiceSummarys: [{}],
                invoiceDocuments: [],
                invoice_date: util.formatDate(new Date(), 'yyyy-MM-dd')
            };

            //新建主发票
            if (Number(invoiceType) === 2) {
                $dialogScope.invoiceInfo.is_main_invoice = '1';
            }

            //获取现有发票信息
            if (oldInvoiceId) {
                $.ajax({
                    url: apiPrefix + 'invoice/get-invoice-info',
                    type: 'get',
                    dataType: 'json',
                    data: {
                        invoiceId: oldInvoiceId
                    },
                    success(res) {
                        if (res.retCode === '0') {
                            const invoiceData = res.data;
                            if (invoiceData) {
                                $dialogScope.invoiceInfo = invoiceData;

                                //复制发票清空信息
                                if (Number(invoiceType) === 3) {
                                    $dialogScope.invoiceInfo.invoice_id = '';
                                    $dialogScope.invoiceInfo.contract_id = '';
                                    $dialogScope.invoiceInfo.is_child_invoice = '';
                                    $dialogScope.invoiceInfo.is_lose = '';
                                    $dialogScope.invoiceInfo.is_receipt = '';
                                    $dialogScope.invoiceInfo.is_red_invoice = '';
                                    $dialogScope.invoiceInfo.payment_amount = '';
                                    $dialogScope.invoiceInfo.receivables_amount = '';
                                    $dialogScope.invoiceInfo.red_by_invoice_id = '';
                                }
                                //查看发票
                                if (Number(invoiceType) === 5) {
                                    $dialogScope.invoiceInfo.editMode = 1;
                                }

                                //红冲此发票
                                if (Number(invoiceType) === 6) {
                                    $dialogScope.invoiceInfo.red_by_invoice_id = $dialogScope.invoiceInfo.invoice_id;
                                    $dialogScope.invoiceInfo.invoice_id = null; //红冲发票新增记录
                                    $dialogScope.invoiceInfo.is_red_invoice = 1;
                                    $dialogScope.invoiceInfo.invoice_amount = $dialogScope.invoiceInfo.invoice_amount >
                                        0 ?
                                        -$dialogScope.invoiceInfo.invoice_amount :
                                        $dialogScope.invoiceInfo.invoice_amount;

                                    $.each($dialogScope.invoiceInfo.invoiceSummarys, function (i, d) {
                                        d.summary_amount = -Math.abs(d.summary_amount);
                                    });
                                }

                                //获取申请人和开票单位
                                if ($dialogScope.invoiceInfo.user_name) {
                                    $('#idProposer').select2('data', {
                                        id: $dialogScope.invoiceInfo.proposer_id,
                                        text: $dialogScope.invoiceInfo.user_name
                                    });
                                }
                                $dialogScope.$applyAsync();
                            }
                        } else {
                            util.alert(res.errMsg);
                        }
                    },
                    error() {
                        util.alert('系统维护，请稍候重试');
                    }
                });
            }

            //新建发票摘要
            $dialogScope.newInvoiceAbstract = function () {
                const items = $dialogScope.invoiceInfo.invoiceSummarys;
                const summary = {};
                items.push(summary);
            };

            //删除发票摘要
            $dialogScope.removeInvoiceAbstract = function (idx) {
                $dialogScope.invoiceInfo.invoiceSummarys.splice(idx, 1);
            };

            //附件上传初始化
            $('#fileupload').fileupload({
                dataType: 'json',
                url: apiPrefix + '/common/file/upload-document',
                acceptFileTypes: /(\.|\/)(xls?x|doc?x|pdf|msg)$/i,
                maxFileSize: 10000000,
                add(e, data) {
                    // 大小限制
                    if (data.files.length > 0) {
                        if (data.files[0].size > config.uploader.max_file_size) {
                            util.alert('文件大小超出' + config.uploader.max_file_size_text + '，无法上传。');
                            return;
                        }
                    }
                    data.submit();
                    ui.loading('', '正在上传…');
                    $('#fileupload_error').hide();
                },
                done(e, data) {
                    const res = data.result;
                    if (Number(res.retCode) === 0) {
                        ui.removeLoading();
                        const document = {
                            __type: 'add',
                            document_id: data._time,
                            document_name: data.files[0].name,
                            document_ext_name: '',
                            document_path: res.data.path,
                            business_id: ''
                        };
                        if (!$dialogScope.invoiceInfo.invoiceDocuments) {
                            $dialogScope.invoiceInfo.invoiceDocuments = [];
                        }
                        $dialogScope.invoiceInfo.invoiceDocuments.push(document);
                        $dialogScope.$applyAsync();

                        $('#fileupload_error').html('');
                        $('#fileupload_error').hide();
                    } else {
                        ui.removeLoading();
                        $('#fileupload_error').html('上传失败:' + res.errMsg);
                        $('#fileupload_error').show();
                    }
                },
                fail(e, data) {
                    $('#fileupload_error').html('上传失败:' + data.errorThrown);
                    $('#fileupload_error').show();
                    ui.removeLoading();
                },
                always() {
                    ui.removeLoading();
                }
            });

            /**
             * 删除附件
             * @param data
             * @param id
             */
            $dialogScope.delAttachment = function (item, idx) {
                if (item.__type === 'add') {
                    $dialogScope.invoiceInfo.invoiceDocuments.splice(idx, 1);
                } else {
                    angular.extend(item, {
                        __type: 'delete'
                    });
                }
                $dialogScope.$applyAsync();
            };
            $dialogScope.$applyAsync();
        },
        editInvoiceSave($data, $dialog, $dialogScope, callback, pageIndex, invoiceType) {
            const item = $dialogScope.invoiceInfo;

            //校验
            if ($('.error:visible').length) {
                return false;
            }

            if (invoiceType !== 6) {
                if (item.invoice_code.length > 20) {
                    util.alert('发票代码不能大于20字符');
                    return false;
                }

                if (item.invoice_no.length > 20) {
                    util.alert('发票号码不能大于20字符');
                    return false;
                }

                if (item.customer_name.length > 100) {
                    util.alert('客户名称不能大于100字符');
                    return false;
                }

                if (!(parseFloat(item.invoice_amount) > 0)) {
                    util.alert('开票金额必须大于0');
                    return false;
                } else if (item.invoice_amount.length > 20) {
                    util.alert('开票金额不能大于20字符');
                    return false;
                }
            } else if (parseFloat(item.invoice_amount) >= 0) {
                //红冲发票的金额必须为负数
                util.alert('红冲中的开票金额只能为负数！');
                return false;
            }

            //发票摘要
            const summarys = item.invoiceSummarys;
            let summary;
            let sum = 0;
            for (let i = 0; i < summarys.length; i += 1) {
                summary = summarys[i]
                if (invoiceType !== 6 && !(parseFloat(summary.summary_amount) > 0)) {
                    util.alert('摘要金额必须大于0');
                    return false;
                } else if (summary.summary_amount.length > 20) {
                    util.alert('摘要金额不能大于20字符');
                    return false;
                }

                //计算摘要金额总和
                sum += parseFloat(summary.summary_amount);
            }

            /**
             * 判断开票金额是否与摘要金额相等
             */
            if (Number(item.invoice_amount) !== Number(sum)) {
                util.alert('开票金额与摘要金额总和不相等');
                return false;
            }
            $.ajax({
                url: apiPrefix + 'invoice/save-invoice',
                type: 'post',
                dataType: 'json',
                data: item,
                success(res) {
                    if (Number(res.retCode) === 0) {
                        $dialog.close();
                        util.alert('保存成功');
                        if (callback) {
                            callback(pageIndex);
                        }
                    } else {
                        util.alert(res.errMsg);
                    }
                },
                error() {
                    util.alert('系统维护，请稍候重试');
                }
            });
            return false;
        }
    };
}]).controller('invoiceListCtrl', [
    '$scope', 'invoiceService', 'appservice',
    function ($scope, invoiceService, appservice) {
        appservice.name = '明源云客-发票管理';
        $scope.invoiceService = invoiceService;

        //发票列表
        $scope.invoices = [];
        //发票批量导入模板地址
        $scope.invoiceImportTpl = "http://ci-yunketest.oss-cn-shenzhen.aliyuncs.com/%E5%8F%91%E7%A5%A8%E6%89%B9%E9%87%8F%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xls"
        //筛选列表
        $scope.filterDataType = [{
            name: '全部',
            selected: true,
            value: '-1'
        }, {
            name: '主发票',
            value: '1'
        }, {
            name: '普通发票',
            value: '0'
        }];
        $scope.filterDataStatus = [{
            name: '全部',
            selected: true,
            value: '-1'
        }, {
            name: '未关联',
            value: '0'
        }, {
            name: '已关联',
            value: '1'
        }];
        $scope.invoiceMixReceipt = [{
            name: '否',
            selected: true,
            value: '0'
        }, {
            name: '是',
            value: '1'
        }]
        $scope.changeQuery = function () {
            $scope.query.execute();
        }

        /**
         * 判断查询时间
         * @param a
         * @param b
         * @returns {boolean}
         */
        const compareDate = function (a, b) {
            let startTime
            let endTime
            if (a) {
                const arrA = a.split('-');
                const start = new Date(arrA[0], arrA[1], arrA[2]);
                startTime = start.getTime();
            }

            if (b) {
                const arrB = b.split('-');
                const end = new Date(arrB[0], arrB[1], arrB[2]);
                endTime = end.getTime();
            }
            return startTime && endTime && startTime > endTime
        };

        function getExtraQuery(parms) {
            //收集过滤条件
            const filterType = _.filter($scope.filterDataType, "selected");
            if (filterType.length) {
                parms.is_main_invoice = filterType[0].value;
            }
            const filterStatus = _.filter($scope.filterDataStatus, "selected");
            if (filterStatus.length) {
                parms.invoice_status = filterStatus[0].value;
            }
            const invoiceMixReceipt = _.filter($scope.invoiceMixReceipt, "selected");
            if (invoiceMixReceipt.length) {
                parms.invoice_mix_receipt = invoiceMixReceipt[0].value;
            }
        }

        //查询条件
        $scope.query = {
            searchKey: '',
            invoice_begin_date: '',
            invoice_end_date: '',
            execute(page) {
                const pageInx = page || 1;
                const parms = {
                    searchKey: this.searchKey,
                    invoice_begin_date: this.invoice_begin_date,
                    invoice_end_date: this.invoice_end_date,
                    pageIndex: page,
                    pageSize: 10
                };

                if (compareDate(this.invoice_begin_date, this.invoice_end_date)) {
                    util.alert('开始时间不得大于结束时间');
                    return;
                }

                getExtraQuery(parms);

                $.ajax({
                    url: apiPrefix + 'invoice/get-invoice-list-by-page',
                    type: 'get',
                    dataType: 'json',
                    data: parms,
                    success(res) {
                        if (res.retCode === '0') {
                            const data = res.data;
                            $scope.invoices = data.items;
                            $scope.total = data.total;
                            $scope.$applyAsync();
                            $scope.getPage(pageInx);
                        } else {
                            util.alert(res.errMsg);
                        }
                    },
                    error() {
                        util.alert('系统维护，请稍候重试！');
                    }
                });
            }
        };

        $scope.downloadInvoices = function () {
            const params = {
                invoice_begin_date: $scope.query.invoice_begin_date,
                invoice_end_date: $scope.query.invoice_end_date,
                searchKey: $scope.query.searchKey,
                is_receipt: 0
            };
            getExtraQuery(params);
            const url = '/api/index.php?r=/invoice/export-invoice&' + $.param(params);
            window.location.href = url;
        };

        $scope.downloadOtherDetails = function () {
            const params = {
                invoice_begin_date: $scope.query.invoice_begin_date,
                invoice_end_date: $scope.query.invoice_end_date,
                searchKey: $scope.query.searchKey
            };
            getExtraQuery(params);
            const url = '/api/index.php?r=/invoice/export-un-invoice-payment&' + $.param(params);
            window.location.href = url;
        };

        $scope.downloadReceipt = function () {
            const params = {
                invoice_begin_date: $scope.query.invoice_begin_date,
                invoice_end_date: $scope.query.invoice_end_date,
                searchKey: $scope.query.searchKey,
                is_receipt: 1
            };
            getExtraQuery(params);
            const url = '/api/index.php?r=/invoice/export-invoice&' + $.param(params);
            window.location.href = url;
        };

        //删除发票
        $scope.removeInvoice = function (id) {
            util.confirm('确定要删除此发票吗？', {
                ok() {
                    $.ajax({
                        url: apiPrefix + 'invoice/delete-invoice',
                        type: 'get',
                        dataType: 'json',
                        data: {
                            invoiceId: id
                        },
                        success(res) {
                            if (res.retCode === '0') {
                                $scope.query.execute($scope.page_index);
                                util.alert('删除成功');
                            } else {
                                util.alert(res.errMsg);
                            }
                        },
                        error() {
                            util.alert('系统维护，请稍候重试！');
                        }
                    });
                }
            });
        };

        //标记遗失
        $scope.markLoss = function (id) {
            util.confirm('确定标记遗失此发票吗？', {
                ok() {
                    $.ajax({
                        url: apiPrefix + 'invoice/do-lose',
                        type: 'get',
                        dataType: 'json',
                        data: {
                            invoiceId: id
                        },
                        success(res) {
                            if (res.retCode === '0') {
                                $scope.query.execute($scope.page_index);
                                util.alert('标记成功');
                            } else {
                                util.alert(res.errMsg);
                            }
                        },
                        error() {
                            util.alert('系统维护，请稍候重试！');
                        }
                    });
                }
            });
        };

        //翻页控件
        $scope.getPage = function (page) {
            $scope.page_index = page || 1
            const pageInx = $scope.page_index;
            $scope.startPageIndex = (pageInx - 1) * 10;
            $('#pagination').pagination($scope.total, {
                current_page: pageInx - 1,
                num_edge_entries: 1, //边缘页数
                num_display_entries: 4, //主体页数
                callback(pageIndex) {
                    $scope.page_index = pageIndex;
                    $scope.startPageIndex = (pageIndex - 1) * 10;
                    $scope.query.execute(pageIndex);
                },
                items_per_page: 10 //每页显示10项
            });
        };

        $scope.rowDbClick = function (index) {
            const $readButton = $('#readInvoiceButton' + index);
            if ($readButton.length > 0) {
                $readButton.trigger('click');
            } else {
                $('#editInvoiceButton' + index).trigger('click');
            }
        };
        //页面初始化
        $scope.init = function () {
            $scope.query.execute();
        };
        $scope.init();
        //附件上传初始化
        setTimeout(function () {
            $('#importInvoice').fileupload({
                dataType: 'json',
                url: apiPrefix + "invoice/import-invoice",
                add(e, data) {
                    data.submit();
                    ui.loading('', '正在上传…');
                },
                done(e, data) {
                    const res = data.result;
                    if (res.retCode === "0") {
                        util.alert("导入成功", { ok: () => window.location.reload(true) })
                    } else {
                        let download = "";
                        if (res.data) {
                            download = "<p><a href='" + res.data + "'>点击此链接，下载失败清单</a><p>";
                        }
                        util.alert(
                            "导入失败:"
                            + res.errMsg
                            + download, { ok: () => window.location.reload(true) }
                        );
                    }
                },
                fail() {
                    util.alert("上传失败");
                },
                always() {
                    ui.removeLoading();
                }
            });
        }, 0);
    }
]);